//
// Created by wujehy on 2020/8/30.
//

#ifndef MQTTCLIENT_THREADPOOL_H
#define MQTTCLIENT_THREADPOOL_H


#include <thread>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <functional>
#include <vector>
#include <queue>

class ThreadPool
{
public:
    using Task = std::function<void()>;

    explicit ThreadPool(int num) : _thread_num(num), _is_running(false) {}

    ~ThreadPool();

    void start();

    void stop();

    void appendTask(const Task &task);

    ThreadPool(const ThreadPool &) = delete;

    ThreadPool &operator=(const ThreadPool &other) = delete;

private:
    void work();

    std::atomic_bool _is_running;
    std::mutex _mtx;
    std::condition_variable _cond;
    int _thread_num;
    std::vector<std::thread> _threads;
    std::queue<Task> _tasks;
};


#endif //MQTTCLIENT_THREADPOOL_H
